package com.mt.skyhoist.ui.activity;

import static com.mt.skyhoist.ui.activity.ScanDeviceService.SelectedChange;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;

import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.view.WheelView;
import com.mt.skyhoist.R;
import com.mt.skyhoist.util.GlobalVariable;
import com.mt.skyhoist.util.view.LockLinearlayout;
import com.mt.sdk.ble.base.MTSeriaBase;
import com.mt.sdk.ble.model.BLEBaseAction.Option;
import com.mt.sdk.ble.model.WriteCharactAction;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


public class ControlFragment extends Fragment {
	private Logger log = LoggerFactory.getLogger("ControlFragment");
	private GlobalVariable mGlobalVariable;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mGlobalVariable = GlobalVariable.getinstance();
	}

	private LockLinearlayout view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (view != null) {
			return view;
		}

		view = (LockLinearlayout)inflater.inflate(R.layout.fragment_control, container, false);

		initView();

		return view;
	}

	// 初始化控件
	private RadioButton left_btn;
	private RadioButton both_btn;
	private RadioButton right_btn;
	private Button up_btn;
	private Button down_btn;
	private WheelView wheelView;
//	private ToggleButton autolevel_btn;

	private void initView() {
		left_btn = (RadioButton) view.findViewById(R.id.left_btn);
		both_btn = (RadioButton) view.findViewById(R.id.both_btn);
		right_btn = (RadioButton) view.findViewById(R.id.right_btn);
		up_btn = (Button) view.findViewById(R.id.up_btn);
		down_btn = (Button) view.findViewById(R.id.down_btn);
		wheelView = (WheelView) view.findViewById(R.id.wheelview);
//		autolevel_btn = (ToggleButton) view.findViewById(R.id.autolevel_btn);
		
		both_btn.setChecked(true);

		up_btn.setOnTouchListener(myOnTouchListener);
		down_btn.setOnTouchListener(myOnTouchListener);

		wheelView.setAdapter(wheelAdapter);
		wheelView.setCyclic(false);
		wheelView.setItemsVisibleCount(3);
		wheelView.setDividerType(WheelView.DividerType.FILL);
		wheelView.setTextColorCenter(getResources().getColor(R.color.colorPrimary));
		wheelView.setTextSize(30);
		wheelView.setTextColorOut(getResources().getColor(R.color.colorPrimary));
	}

	private boolean isChecked = false;
	private long checkedTime = 0;
	private OnTouchListener myOnTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (v == up_btn) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) { // 按下
					if(left_btn.isChecked()){
						datas[0] = 0x01;
					}else if(right_btn.isChecked()){
						datas[0] = 0x03;
					}else if(both_btn.isChecked()){
//						if(autolevel_btn.isChecked()){
//							datas[0] = 0x07;
//						}else{
							datas[0] = 0x05;
//						}
					}
					checkedTime = System.currentTimeMillis();
					handl.sendEmptyMessage(SENDTIME);
					return false;
				}
				if(event.getAction() == MotionEvent.ACTION_UP){  // 松开
					handl.removeMessages(SENDTIME);
					return false;
				}
				return false;
			}
			
			if (v == down_btn) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) { // 按下
					if(left_btn.isChecked()){
						datas[0] = 0x02;
					}else if(right_btn.isChecked()){
						datas[0] = 0x04;
					}else if(both_btn.isChecked()){
//						if(autolevel_btn.isChecked()){
//							datas[0] = 0x08;
//						}else{
							datas[0] = 0x06;
//						}
					}

					isChecked = true;
					checkedTime = System.currentTimeMillis();
					handl.sendEmptyMessage(SENDTIME);
					return false;
				}
				if(event.getAction() == MotionEvent.ACTION_UP){  // 松开
					isChecked = false;
					handl.removeMessages(SENDTIME);
					return false;
				}
				return false;
			}

			return false;
		}
	};

	private WheelAdapter wheelAdapter = new WheelAdapter() {
		@Override
		public int getItemsCount() {
			int selectedGroup = mGlobalVariable.getMixDatas().getSelectgrounp();
			if(selectedGroup == -1){
				return 1;
			}
			return mGlobalVariable.getDeviceGroup().get(selectedGroup).size();
		}

		@Override
		public String getItem(int index) {
			try {
				int selectedGroup = mGlobalVariable.getMixDatas().getSelectgrounp();
				if(selectedGroup == -1){
					return "";
				}
				return mGlobalVariable.getDeviceGroup().get(selectedGroup).get(index).getName();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}

		@Override
		public int indexOf(Object o) {
			return 0;
		}
	};


	@Override
	public void onResume() {
		super.onResume();
		EventBus.getDefault().register(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		EventBus.getDefault().unregister(this);
		isChecked = false;
		handl.removeMessages(SENDTIME);
	}

	// 停止动作
	public void stopAction(){
		log.debug("stopAction");
		handl.removeMessages(SENDTIME);
	}

	// 设置连接
	public void setBles(List<MTSeriaBase> bles) {
	}
	
	// 设置是否所有设备都连接成功
	private boolean connectStatues = false;
	public void setConnectStatues(boolean statues){
		this.connectStatues = statues;
	}
	
	private byte[] datas = new byte[] { 0x01 };
	private final int SENDTIME = 5;
	private Handler handl = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == SENDTIME) {
				if(System.currentTimeMillis() - checkedTime > 1000) {  // 1秒后生效
					if (!up_btn.isPressed() && !down_btn.isPressed()) {
						isChecked = false;
						return;
					}
				}
				if(mGlobalVariable.bles == null){
					log.debug("bles == null");
					return;
				}

				if(connectStatues){   // 如果设备没有全部连接上，则不要操作
					for (MTSeriaBase mtSeriaBase : mGlobalVariable.bles) {
						mtSeriaBase.addWriteDatasAction(new WriteCharactAction(null, datas, new Option(1000)));
					}
				}
				handl.sendEmptyMessageDelayed(SENDTIME, 150); // 150ms发送一次
				return;
			}
		}

	};

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onMessageEvent(Integer event) {
		switch (event) {
			case SelectedChange:
				wheelView.setAdapter(wheelAdapter);
				wheelView.setCurrentItem(0);
				break;
		}
	}
}
